import axios from 'axios';
import { getConfig } from './utils';
import { handleHighDprVague } from './canvas';

interface ImageInfo {
  height: number;
  pixelRatio: number;
  width: number;
  x: number;
  y: number;
}

interface SpriteConfig {
  [key: string]: ImageInfo;
}

let cacheConfig: SpriteConfig | null = null;
let cacheImage: HTMLImageElement | null = null;

/**
 * 根据图片名称截取精灵图中的图片
 * @param spriteImage HTMLImageElement - 精灵图
 * @param imageName string - 图片名称
 * @returns HTMLCanvasElement - 包含所需图片的画布
 */
export async function getImageFromSprite(imageName: string): Promise<HTMLCanvasElement | void> {
  const spritePath = getConfig().appSettings.sprite;
  const res = await Promise.all([axios.get(`${spritePath}.json`), axios.get(`${spritePath}.png`)]);
  if (!res || !res[0]?.data || !res[1]?.data) return;
  cacheConfig = res[0].data;
  cacheImage = new Image();
  const imageInfo = cacheConfig![imageName];
  if (!imageInfo) return;
  const canvas = document.createElement('canvas');
  canvas.width = imageInfo.width;
  canvas.height = imageInfo.height;
  const ctx = canvas.getContext('2d');
  if (!ctx) return;
  handleHighDprVague(canvas, ctx);
  ctx.drawImage(cacheImage, imageInfo.x, imageInfo.y, imageInfo.width, imageInfo.height, 0, 0, imageInfo.width, imageInfo.height);
  return canvas;
}
